/**
 * 活动执行管理页面JavaScript
 * 基于Apple Design System的交互设计
 * 版本：v1.0
 * 创建时间：2025-07-20
 */

// 全局变量
let currentStep = 'preparation';
let checklistData = [];
let checkinData = [];
let activityRecords = [];
let countdownTimer = null;
let activityTimer = null;

// DOM 元素
const executionSteps = document.querySelectorAll('.nav-step');
const executionContents = document.querySelectorAll('.execution-content');
const quickCheckinBtn = document.getElementById('quick-checkin-btn');
const startActivityBtn = document.getElementById('start-activity-btn');
const countdownTimeSpan = document.getElementById('countdown-time');
const checkinCountSpan = document.getElementById('checkin-count');
const expectedCountSpan = document.getElementById('expected-count');
const checkinRateSpan = document.getElementById('checkin-rate');
const activityDurationSpan = document.getElementById('activity-duration');

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeEventListeners();
    loadChecklistData();
    loadCheckinData();
    loadActivityRecords();
    initializeCountdown();
    updatePreparationProgress();
    updateCheckinStats();
});

// 初始化事件监听器
function initializeEventListeners() {
    // 执行阶段切换
    executionSteps.forEach(step => {
        step.addEventListener('click', () => {
            switchExecutionStep(step.dataset.step);
        });
    });
    
    // 快速签到
    quickCheckinBtn.addEventListener('click', openQuickCheckin);
    
    // 开始活动
    if (startActivityBtn) {
        startActivityBtn.addEventListener('click', startActivity);
    }
    
    // 签到方式切换
    initializeCheckinMethods();
    
    // 搜索功能
    initializeCheckinSearch();
    
    // 签到列表筛选
    initializeCheckinFilters();
    
    // 模态框事件
    document.addEventListener('click', handleModalClick);
    document.addEventListener('keydown', handleKeyDown);
}

// 切换执行阶段
function switchExecutionStep(step) {
    currentStep = step;
    
    // 更新导航状态
    executionSteps.forEach(stepEl => {
        stepEl.classList.toggle('active', stepEl.dataset.step === step);
    });
    
    // 显示对应内容
    executionContents.forEach(content => {
        if (content.id === `${step}-content`) {
            content.style.display = 'block';
        } else {
            content.style.display = 'none';
        }
    });
    
    // 特殊处理
    if (step === 'checkin') {
        updateCheckinDisplay();
    } else if (step === 'process') {
        startActivityTimer();
    }
}

// 加载检查清单数据
function loadChecklistData() {
    checklistData = [
        {
            id: 'venue',
            category: 'venue',
            title: '场地确认',
            description: '确认活动场地预订和布置',
            completed: true,
            completedTime: '2025-07-24 16:30',
            responsible: '张经理',
            priority: 'normal'
        },
        {
            id: 'equipment',
            category: 'venue',
            title: '设备调试',
            description: '投影仪、音响、麦克风等设备测试',
            completed: true,
            completedTime: '2025-07-25 13:00',
            responsible: '李技术员',
            priority: 'normal'
        },
        {
            id: 'signage',
            category: 'venue',
            title: '指示牌布置',
            description: '活动指示牌、签到台标识等',
            completed: false,
            deadline: '2025-07-25 14:00',
            responsible: '王助理',
            priority: 'normal'
        },
        {
            id: 'materials',
            category: 'materials',
            title: '宣传资料',
            description: '产品手册、宣传单页、视频资料准备',
            completed: true,
            completedTime: '2025-07-24 18:00',
            responsible: '市场部',
            priority: 'normal'
        },
        {
            id: 'refreshments',
            category: 'materials',
            title: '茶点准备',
            description: '茶水、点心、水果等茶点安排',
            completed: true,
            completedTime: '2025-07-25 12:30',
            responsible: '行政部',
            priority: 'normal'
        },
        {
            id: 'gifts',
            category: 'materials',
            title: '礼品准备',
            description: '客户伴手礼、纪念品准备',
            completed: true,
            completedTime: '2025-07-25 10:00',
            responsible: '采购部',
            priority: 'normal'
        },
        {
            id: 'staff',
            category: 'staff',
            title: '工作人员到位',
            description: '主持人、接待员、技术员等人员安排',
            completed: true,
            completedTime: '2025-07-25 13:30',
            responsible: '人事部',
            priority: 'normal'
        },
        {
            id: 'checkin-table',
            category: 'staff',
            title: '签到表准备',
            description: '客户签到表、座位安排表等',
            completed: true,
            completedTime: '2025-07-25 14:00',
            responsible: '客服部',
            priority: 'normal'
        },
        {
            id: 'emergency-plan',
            category: 'staff',
            title: '应急预案确认',
            description: '突发情况处理方案、联系方式确认',
            completed: false,
            deadline: '2025-07-25 14:15',
            responsible: '安全员',
            priority: 'urgent'
        }
    ];
}

// 加载签到数据
function loadCheckinData() {
    checkinData = [
        {
            id: 1,
            customerId: 'CRM2025000001',
            customerName: '张大爷',
            customerPhone: '138****8001',
            customerAvatar: '张',
            checkedIn: true,
            checkinTime: '14:25',
            companion: '张大妈（老伴）',
            seatNumber: 'A1-05',
            status: 'early'
        },
        {
            id: 2,
            customerId: 'CRM2025000002',
            customerName: '李大妈',
            customerPhone: '139****8002',
            customerAvatar: '李',
            checkedIn: true,
            checkinTime: '14:32',
            companion: '',
            seatNumber: 'A2-03',
            status: 'normal'
        },
        {
            id: 3,
            customerId: 'CRM2025000003',
            customerName: '王先生',
            customerPhone: '137****8003',
            customerAvatar: '王',
            checkedIn: false,
            checkinTime: '',
            companion: '',
            seatNumber: 'B1-08',
            status: 'absent'
        }
        // 更多签到数据...
    ];
}

// 加载活动记录
function loadActivityRecords() {
    activityRecords = [
        {
            id: 1,
            time: '14:30',
            title: '活动正式开始',
            description: '主持人开场致辞，介绍活动流程',
            recorder: '张经理',
            status: 'completed'
        },
        {
            id: 2,
            time: '14:45',
            title: '产品介绍环节',
            description: '专业导游开始介绍桂林山水3日游线路，客户反应热烈',
            recorder: '李导游',
            status: 'completed'
        },
        {
            id: 3,
            time: '15:20',
            title: '互动问答环节',
            description: '客户积极提问，主要关心价格、住宿条件和安全问题',
            recorder: '王客服',
            status: 'current'
        },
        {
            id: 4,
            time: '15:45',
            title: '优惠政策介绍',
            description: '预计介绍特殊优惠政策和限时优惠',
            recorder: '',
            status: 'future'
        },
        {
            id: 5,
            time: '16:15',
            title: '现场咨询服务',
            description: '一对一客户咨询和签约服务',
            recorder: '',
            status: 'future'
        }
    ];
}

// 初始化倒计时
function initializeCountdown() {
    const activityStartTime = new Date('2025-07-25 14:30:00');
    const now = new Date();
    
    // 如果活动已经开始，显示进行时间
    if (now >= activityStartTime) {
        if (countdownTimeSpan) {
            countdownTimeSpan.textContent = '活动进行中';
            countdownTimeSpan.style.color = 'var(--apple-green)';
        }
        return;
    }
    
    countdownTimer = setInterval(() => {
        const now = new Date();
        const timeDiff = activityStartTime - now;
        
        if (timeDiff <= 0) {
            clearInterval(countdownTimer);
            if (countdownTimeSpan) {
                countdownTimeSpan.textContent = '活动开始';
                countdownTimeSpan.style.color = 'var(--apple-green)';
            }
            return;
        }
        
        const hours = Math.floor(timeDiff / (1000 * 60 * 60));
        const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);
        
        const timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        
        if (countdownTimeSpan) {
            countdownTimeSpan.textContent = timeString;
        }
    }, 1000);
}

// 更新准备进度
function updatePreparationProgress() {
    const totalItems = checklistData.length;
    const completedItems = checklistData.filter(item => item.completed).length;
    const progress = (completedItems / totalItems) * 100;
    
    // 更新进度圆环
    const progressBar = document.querySelector('.progress-bar');
    if (progressBar) {
        const circumference = 2 * Math.PI * 25; // r = 25
        const offset = circumference - (progress / 100) * circumference;
        progressBar.style.strokeDashoffset = offset;
    }
    
    // 更新进度文本
    const progressText = document.querySelector('.progress-text');
    if (progressText) {
        progressText.textContent = `${Math.round(progress)}%`;
    }
    
    const progressDetail = document.querySelector('.progress-detail');
    if (progressDetail) {
        progressDetail.textContent = `${completedItems}/${totalItems}项已完成`;
    }
}

// 更新签到统计
function updateCheckinStats() {
    const checkedInCount = checkinData.filter(item => item.checkedIn).length;
    const expectedCount = checkinData.length;
    const checkinRate = expectedCount > 0 ? (checkedInCount / expectedCount * 100).toFixed(1) : 0;
    
    if (checkinCountSpan) checkinCountSpan.textContent = checkedInCount;
    if (expectedCountSpan) expectedCountSpan.textContent = expectedCount;
    if (checkinRateSpan) checkinRateSpan.textContent = `${checkinRate}%`;
}

// 初始化签到方式切换
function initializeCheckinMethods() {
    const methodBtns = document.querySelectorAll('.method-btn');
    const checkinAreas = document.querySelectorAll('.checkin-input-area');
    
    methodBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const method = this.dataset.method;
            
            // 更新按钮状态
            methodBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            
            // 显示对应区域
            checkinAreas.forEach(area => {
                area.style.display = area.id === `${method}-checkin` ? 'block' : 'none';
            });
        });
    });
}

// 初始化签到搜索
function initializeCheckinSearch() {
    const searchInput = document.getElementById('checkin-search');
    const suggestions = document.getElementById('search-suggestions');
    
    if (!searchInput) return;
    
    searchInput.addEventListener('input', function() {
        const query = this.value.toLowerCase().trim();
        
        if (query.length < 2) {
            suggestions.style.display = 'none';
            return;
        }
        
        // 模拟搜索结果
        const results = checkinData.filter(customer => 
            customer.customerName.toLowerCase().includes(query) ||
            customer.customerPhone.includes(query)
        );
        
        if (results.length > 0) {
            suggestions.innerHTML = results.map(customer => `
                <div class="suggestion-item" onclick="selectCustomerForCheckin(${customer.id})">
                    <div class="suggestion-avatar">${customer.customerAvatar}</div>
                    <div class="suggestion-info">
                        <div class="suggestion-name">${customer.customerName}</div>
                        <div class="suggestion-phone">${customer.customerPhone}</div>
                    </div>
                    <div class="suggestion-status">
                        ${customer.checkedIn ? '已签到' : '未签到'}
                    </div>
                </div>
            `).join('');
            suggestions.style.display = 'block';
        } else {
            suggestions.style.display = 'none';
        }
    });
    
    // 点击外部关闭建议
    document.addEventListener('click', function(e) {
        if (!searchInput.contains(e.target) && !suggestions.contains(e.target)) {
            suggestions.style.display = 'none';
        }
    });
}

// 初始化签到筛选
function initializeCheckinFilters() {
    const filterBtns = document.querySelectorAll('.filter-btn');
    
    filterBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const filter = this.dataset.filter;
            
            // 更新按钮状态
            filterBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            
            // 筛选显示
            filterCheckinList(filter);
        });
    });
}

// 筛选签到列表
function filterCheckinList(filter) {
    const rows = document.querySelectorAll('.checkin-row');
    
    rows.forEach(row => {
        const customerId = parseInt(row.dataset.customerId);
        const customer = checkinData.find(c => c.id === customerId);
        
        if (!customer) return;
        
        let shouldShow = true;
        
        switch (filter) {
            case 'checked':
                shouldShow = customer.checkedIn;
                break;
            case 'absent':
                shouldShow = !customer.checkedIn;
                break;
            case 'all':
            default:
                shouldShow = true;
                break;
        }
        
        row.style.display = shouldShow ? 'table-row' : 'none';
    });
}

// 更新签到显示
function updateCheckinDisplay() {
    renderCheckinTable();
    updateCheckinStats();
}

// 渲染签到表格
function renderCheckinTable() {
    const tbody = document.getElementById('checkin-table-body');
    if (!tbody) return;
    
    tbody.innerHTML = '';
    
    checkinData.forEach(customer => {
        const row = createCheckinRow(customer);
        tbody.appendChild(row);
    });
}

// 创建签到行
function createCheckinRow(customer) {
    const row = document.createElement('tr');
    row.className = `checkin-row ${customer.checkedIn ? 'checked-in' : 'absent'}`;
    row.dataset.customerId = customer.id;
    
    const timeDisplay = customer.checkedIn ? 
        `<div class="time-display">${customer.checkinTime}</div>
         <div class="time-status ${customer.status}">${getStatusText(customer.status)}</div>` :
        `<span class="time-empty">未签到</span>`;
    
    const companionDisplay = customer.companion ?
        `<span class="companion-info">${customer.companion}</span>` :
        `<span class="companion-empty">${customer.checkedIn ? '无' : '-'}</span>`;
    
    const seatDisplay = customer.checkedIn ?
        `<span class="seat-number">${customer.seatNumber}</span>` :
        `<span class="seat-reserved">${customer.seatNumber}</span>`;
    
    const statusDisplay = customer.checkedIn ?
        `<span class="status-badge status-checked">已签到</span>` :
        `<span class="status-badge status-absent">未到场</span>`;
    
    const actionButtons = customer.checkedIn ?
        `<button class="action-btn" title="编辑信息" onclick="editCheckinInfo(${customer.id})">
            <i class="fas fa-edit"></i>
        </button>
        <button class="action-btn" title="取消签到" onclick="cancelCheckin(${customer.id})">
            <i class="fas fa-times"></i>
        </button>` :
        `<button class="action-btn primary" title="手动签到" onclick="manualCheckin(${customer.id})">
            <i class="fas fa-check"></i>
        </button>
        <button class="action-btn" title="联系客户" onclick="contactCustomer(${customer.id})">
            <i class="fas fa-phone"></i>
        </button>`;
    
    row.innerHTML = `
        <td class="customer-info">
            <div class="customer-detail">
                <div class="customer-avatar">${customer.customerAvatar}</div>
                <div class="customer-data">
                    <div class="customer-name">${customer.customerName}</div>
                    <div class="customer-phone">${customer.customerPhone}</div>
                </div>
            </div>
        </td>
        <td class="checkin-time">${timeDisplay}</td>
        <td class="companion">${companionDisplay}</td>
        <td class="seat-assignment">${seatDisplay}</td>
        <td class="checkin-status">${statusDisplay}</td>
        <td class="actions">${actionButtons}</td>
    `;
    
    return row;
}

// 开始活动计时器
function startActivityTimer() {
    if (activityTimer) return;
    
    const startTime = new Date();
    
    activityTimer = setInterval(() => {
        const now = new Date();
        const duration = now - startTime;
        
        const hours = Math.floor(duration / (1000 * 60 * 60));
        const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((duration % (1000 * 60)) / 1000);
        
        const timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        
        if (activityDurationSpan) {
            activityDurationSpan.textContent = timeString;
        }
    }, 1000);
}

// 检查清单相关函数
function markChecklistComplete(itemId) {
    const item = checklistData.find(item => item.id === itemId);
    if (item) {
        item.completed = true;
        item.completedTime = new Date().toLocaleString('zh-CN', {
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
        updatePreparationProgress();
        showNotification('检查项已完成', 'success');
    }
}

function viewChecklistDetail(itemId) {
    showNotification('查看检查详情功能正在开发中...', 'info');
}

// 最后确认相关函数
function sendLastReminder() {
    showNotification('正在发送最后提醒给所有确认参加的客户...', 'info');
}

function startActivity() {
    if (confirm('确定要开始活动吗？开始后将进入现场签到阶段。')) {
        switchExecutionStep('checkin');
        showNotification('活动已开始，现在可以进行现场签到', 'success');
    }
}

// 签到相关函数
function selectCustomerForCheckin(customerId) {
    const customer = checkinData.find(c => c.id === customerId);
    if (!customer) return;
    
    if (customer.checkedIn) {
        showNotification('该客户已经签到', 'warning');
        return;
    }
    
    // 执行签到
    customer.checkedIn = true;
    customer.checkinTime = new Date().toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
    });
    customer.status = 'normal';
    
    updateCheckinDisplay();
    showNotification(`${customer.customerName} 签到成功`, 'success');
    
    // 清除搜索
    const searchInput = document.getElementById('checkin-search');
    const suggestions = document.getElementById('search-suggestions');
    if (searchInput) searchInput.value = '';
    if (suggestions) suggestions.style.display = 'none';
}

function startQRScanner() {
    showNotification('二维码扫描功能正在开发中...', 'info');
}

function manualCheckin(customerId) {
    selectCustomerForCheckin(customerId);
}

function editCheckinInfo(customerId) {
    showNotification('编辑签到信息功能正在开发中...', 'info');
}

function cancelCheckin(customerId) {
    const customer = checkinData.find(c => c.id === customerId);
    if (!customer) return;
    
    if (confirm('确定要取消该客户的签到吗？')) {
        customer.checkedIn = false;
        customer.checkinTime = '';
        customer.status = 'absent';
        
        updateCheckinDisplay();
        showNotification('签到已取消', 'success');
    }
}

function contactCustomer(customerId) {
    showNotification('正在为您拨打客户电话...', 'info');
}

function openQuickCheckin() {
    switchExecutionStep('checkin');
}

// 活动过程相关函数
function addActivityRecord() {
    const modal = document.getElementById('activity-record-modal');
    if (modal) {
        // 设置当前时间
        const recordTimeInput = document.getElementById('record-time');
        if (recordTimeInput) {
            const now = new Date();
            const timeString = now.toTimeString().slice(0, 5);
            recordTimeInput.value = timeString;
        }
        
        modal.classList.add('show');
    }
}

function closeActivityRecordModal() {
    const modal = document.getElementById('activity-record-modal');
    if (modal) {
        modal.classList.remove('show');
        
        // 重置表单
        const form = modal.querySelector('form');
        if (form) form.reset();
    }
}

function saveActivityRecord() {
    const form = document.querySelector('.activity-record-form');
    if (!form) return;
    
    const formData = new FormData(form);
    const recordData = Object.fromEntries(formData);
    
    // 验证必填字段
    if (!recordData['record-time'] || !form.querySelector('input[placeholder="请输入事件标题"]').value) {
        showNotification('请填写完整信息', 'warning');
        return;
    }
    
    showNotification('活动记录已保存', 'success');
    closeActivityRecordModal();
}

function markCustomerInterested() {
    showNotification('标记感兴趣客户功能正在开发中...', 'info');
}

function markCustomerIntention() {
    showNotification('标记意向客户功能正在开发中...', 'info');
}

// 工具函数
function getStatusText(status) {
    const statusMap = {
        'early': '提前到达',
        'normal': '正常到达',
        'late': '迟到'
    };
    return statusMap[status] || '正常到达';
}

function goBackToActivity() {
    window.location.href = 'invitation-management.html';
}

// 通用函数
function handleModalClick(event) {
    if (event.target.classList.contains('modal-overlay')) {
        closeActivityRecordModal();
    }
}

function handleKeyDown(event) {
    if (event.key === 'Escape') {
        closeActivityRecordModal();
    }
}

function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `alert alert-${type}`;
    notification.innerHTML = `
        <i class="fas fa-${getNotificationIcon(type)}"></i>
        <span>${message}</span>
    `;
    
    document.body.appendChild(notification);
    
    notification.style.position = 'fixed';
    notification.style.top = '80px';
    notification.style.right = '20px';
    notification.style.zIndex = '9999';
    notification.style.minWidth = '300px';
    notification.style.animation = 'slideInRight 0.3s ease-out';
    
    setTimeout(() => {
        notification.style.animation = 'slideOutRight 0.3s ease-in';
        setTimeout(() => {
            if (document.body.contains(notification)) {
                document.body.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

function getNotificationIcon(type) {
    const iconMap = {
        'info': 'info-circle',
        'success': 'check-circle',
        'warning': 'exclamation-triangle',
        'error': 'times-circle'
    };
    return iconMap[type] || 'info-circle';
}

// 导出函数供HTML使用
window.switchExecutionStep = switchExecutionStep;
window.markChecklistComplete = markChecklistComplete;
window.viewChecklistDetail = viewChecklistDetail;
window.sendLastReminder = sendLastReminder;
window.startActivity = startActivity;
window.selectCustomerForCheckin = selectCustomerForCheckin;
window.startQRScanner = startQRScanner;
window.manualCheckin = manualCheckin;
window.editCheckinInfo = editCheckinInfo;
window.cancelCheckin = cancelCheckin;
window.contactCustomer = contactCustomer;
window.openQuickCheckin = openQuickCheckin;
window.addActivityRecord = addActivityRecord;
window.closeActivityRecordModal = closeActivityRecordModal;
window.saveActivityRecord = saveActivityRecord;
window.markCustomerInterested = markCustomerInterested;
window.markCustomerIntention = markCustomerIntention;
window.goBackToActivity = goBackToActivity;